package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseContorller;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ContractProductVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.*;


@Controller
@RequestMapping("/cargo/contract")
public class ContractController extends BaseContorller {

    @Reference
    private ContractService contractService;

    @RequestMapping(value = "/list",name = "分页查询购销合同列表数据")
    public String findAll(@RequestParam(value = "page",defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize){
        //查询
        ContractExample example = new ContractExample();
        //where company_id=?    andCompanyIdEqualTo
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getCompanyId());
        //细颗粒查询
        User user = getUser();
        Integer degree = user.getDegree();
        //        1-企业管理员
        //        2-管理所有下属部门和人员
        //        3-管理本部门
        //        4-普通员工
        if (degree==4){//普通人员
            criteria.andCreateByEqualTo(user.getId());
        }else if (degree==3){//        3-管理本部门
            criteria.andCreateDeptEqualTo(user.getDeptId());
        }else if (degree==2){
            criteria.andCreateDeptLike(user.getDeptId()+"%");
        }

        //order by
        example.setOrderByClause("create_time desc");
        PageInfo pageInfo = contractService.findAll(example,pageNum,pageSize);
        request.setAttribute("page",pageInfo);
        return "cargo/contract/contract-list";
    }

    @RequestMapping(value = "/toAdd",name = "跳转添加合同页面")
    public String toAdd(){
        return "cargo/contract/contract-add";
    }

    @RequestMapping(value = "/edit",name = "保存合同")
    public String edit(Contract contract){

        if (StringUtils.isEmpty(contract.getId())){//id为空
            contract.setId(UUID.randomUUID().toString());
            contract.setCompanyId(getCompanyId());
            contract.setCompanyName(getCompanyName());
            contract.setState(0);
            contract.setCreateTime(new Date());
            contract.setCreateBy(getUser().getId());//当前登录人细颗粒控制查询
            contract.setCreateDept(getUser().getDeptId());//当前登录人的部门
            contractService.save(contract);

        }else {//id不为空
            contractService.update(contract);
        }


        return "redirect:/cargo/contract/list.do";
    }
    @RequestMapping(value = "/toUpdate",name = "进入合同修改页面")
    public String update(String id){

        Contract contract = contractService.findById(id);
        request.setAttribute("contract",contract);
        return "cargo/contract/contract-add";
    }

    @RequestMapping(value = "/delete",name = "删除合同页面")
    public String delete(String id){

        contractService.delete(id);

        return "redirect:/cargo/contract/list.do";
    }
    @RequestMapping(value = "/submit",name = "提交合同页面")
    public String submit(String id){
        Contract contract = contractService.findById(id);
        contract.setState(1);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }
    @RequestMapping(value = "/cancel",name = "取消合同页面")
    public String cancel(String id){
        Contract contract = contractService.findById(id);
        contract.setState(0);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }


    @RequestMapping(value = "/print",name = "出货表页面")
    public String print(){
        return "cargo/print/contract-print";
    }

    @RequestMapping(value = "/printExcel",name = "导出出货表方法")
    public void printExcel(String inputDate) throws Exception{
        List<ContractProductVo> cpVoList = contractService.findContractProductVoByShipTime(inputDate,getCompanyId());
        //获取模板的路径
        String templateFilePath = session.getServletContext().getRealPath("/make/xlsprint/tOUTPRODUCT.xlsx");
        //获取一个有内容的工作簿
        Workbook workbook = new XSSFWorkbook(new FileInputStream(templateFilePath));
        //大标题
        Sheet sheet = workbook.getSheetAt(0);
        Cell cell = sheet.getRow(0).getCell(1);
        cell.setCellValue(inputDate.replace("-0","年").replace("-","年")+"月出货表");

        //内容
        Row row = sheet.getRow(2);
        CellStyle[] cellStyles = new CellStyle[8];
        for (int i = 1; i <= 8; i++) {
            cellStyles[i-1] = row.getCell(i).getCellStyle();
        }

        int rowIndex=2;
        for (ContractProductVo contractProductVo : cpVoList) {
            row = sheet.createRow(rowIndex);
            row.setHeightInPoints(24);

            //客户名称  合同号  货号  数量  厂家名称  交货期限 船期 贸易条款
            cell=row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName());
            cell.setCellStyle(cellStyles[0]);

            cell=row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo());
            cell.setCellStyle(cellStyles[1]);

            cell=row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo());
            cell.setCellStyle(cellStyles[2]);

            cell=row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());
            cell.setCellStyle(cellStyles[3]);

            cell=row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());
            cell.setCellStyle(cellStyles[4]);

            cell=row.createCell(6);
            cell.setCellValue(contractProductVo.getDeliveryPeriod());
            cell.setCellStyle(cellStyles[5]);

            cell=row.createCell(7);
            cell.setCellValue(contractProductVo.getShipTime());
            cell.setCellStyle(cellStyles[6]);

            cell=row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());//贸易条款
            cell.setCellStyle(cellStyles[7]);

            rowIndex++;

        }

        DownloadUtil downloadUtil = new DownloadUtil();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");

    }


    @RequestMapping(value = "/printExcelEasyExcel",name = "使用EasyExcel导出出货表方法")
    public void printExcelEasyExcel(String inputDate) throws Exception {
        List<ContractProductVo> cpVoList = contractService.findContractProductVoByShipTime(inputDate, getCompanyId());
//        一个流两个头

        String returnName="出货表.xlsx";

        returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置mime类型
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-disposition","attachment;filename="+returnName);

        EasyExcel.write(response.getOutputStream()).head(ContractProductVo.class).sheet("出货表").doWrite(cpVoList);

    }


    @RequestMapping(value = "/printEasyExcelTemplate",name = "使用EasyExcel导出出货表方法")
    public void printEasyExcelTemplate(String inputDate) throws Exception {

        List<ContractProductVo> cpVoList = contractService.findContractProductVoByShipTime(inputDate, getCompanyId());

        //获取模板的路径
        String templateFilePath = session.getServletContext().getRealPath("/make/xlsprint/product.xlsx");
        Map map = new HashMap();
        map.put("time",inputDate.replace("-0","年").replace("-","年")+"月出货表");
        String returnName="出货表.xlsx";

        returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置mime类型
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-disposition","attachment;filename="+returnName);
        //为了构建write对象
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).head(ContractProductVo.class).withTemplate(templateFilePath).build();
        //构建即将写入的sheet对象
        WriteSheet sheet = EasyExcel.writerSheet().build();
        excelWriter.fill(map,sheet);
        excelWriter.fill(cpVoList,sheet);
        excelWriter.finish();

    }



}
